#include "CarDataModel.h"
#include <QRandomGenerator>

CarDataModel::CarDataModel(QObject *parent)
    : QObject(parent), m_rpm(0), m_speed(0), m_temperature(20.5), m_outsideTemp(21.5), m_totalKm(9999), m_remainingKm(205), m_waterTemp(90), m_fuelLevel(75), m_statusMessage("注意：车辆运行至 P 档。"), m_engineRunning(false), m_handbrakeOn(true), m_seatbeltWarning(true), m_headlightsOn(false), m_highBeamOn(false), m_oilLife(65), m_avgSpeed(42.5), m_avgFuelConsumption(7.8), m_tripDistance(0), m_targetRpm(0), m_targetSpeed(0), m_targetWaterTemp(90), m_targetFuelLevel(75)
{
    m_timeTimer = new QTimer(this);
    connect(m_timeTimer, &QTimer::timeout, this, &CarDataModel::updateTime);
    m_timeTimer->start(250); // 每秒更新时间

    m_simulationTimer = new QTimer(this);
    connect(m_simulationTimer, &QTimer::timeout, this, &CarDataModel::simulateData);
    m_simulationTimer->start(50); // 每50毫秒更新一次，使动画更流畅
}

void CarDataModel::setRpm(int rpm)
{
    if (m_rpm != rpm)
    {
        m_rpm = rpm;
        emit rpmChanged();
    }
}

void CarDataModel::setSpeed(int speed)
{
    if (m_speed != speed)
    {
        m_speed = speed;
        emit speedChanged();
    }
}

void CarDataModel::setTemperature(double temperature)
{
    if (m_temperature != temperature)
    {
        m_temperature = temperature;
        emit temperatureChanged();
    }
}

void CarDataModel::setOutsideTemp(double outsideTemp)
{
    if (m_outsideTemp != outsideTemp)
    {
        m_outsideTemp = outsideTemp;
        emit outsideTempChanged();
    }
}

void CarDataModel::setTotalKm(int totalKm)
{
    if (m_totalKm != totalKm)
    {
        m_totalKm = totalKm;
        emit totalKmChanged();
    }
}

void CarDataModel::setRemainingKm(int remainingKm)
{
    if (m_remainingKm != remainingKm)
    {
        m_remainingKm = remainingKm;
        emit remainingKmChanged();
    }
}

void CarDataModel::setWaterTemp(int waterTemp)
{
    if (m_waterTemp != waterTemp)
    {
        m_waterTemp = waterTemp;
        emit waterTempChanged();
    }
}

void CarDataModel::setFuelLevel(int fuelLevel)
{
    if (m_fuelLevel != fuelLevel)
    {
        m_fuelLevel = fuelLevel;
        emit fuelLevelChanged();
    }
}

void CarDataModel::setStatusMessage(const QString &statusMessage)
{
    if (m_statusMessage != statusMessage)
    {
        m_statusMessage = statusMessage;
        emit statusMessageChanged();
    }
}

void CarDataModel::setEngineRunning(bool engineRunning)
{
    if (m_engineRunning != engineRunning)
    {
        m_engineRunning = engineRunning;
        emit engineRunningChanged();

        if (!engineRunning)
        {
            m_targetRpm = 0;
            m_targetSpeed = 0;
            setStatusMessage("发动机已关闭");
        }
        else
        {
            m_targetRpm = 800;
            setStatusMessage("发动机启动");
        }
    }
}

void CarDataModel::setHandbrakeOn(bool handbrakeOn)
{
    if (m_handbrakeOn != handbrakeOn)
    {
        m_handbrakeOn = handbrakeOn;
        emit handbrakeOnChanged();

        if (handbrakeOn)
        {
            m_targetSpeed = 0;
            setStatusMessage("手刹已拉起");
            // 拉起手刹时，安全带显示为未系上
            setSeatbeltWarning(true);
        }
        else
        {
            setStatusMessage("手刹已松开");
            // 松开手刹时，安全带显示为已系上
            setSeatbeltWarning(false);
        }
    }
}

void CarDataModel::setSeatbeltWarning(bool seatbeltWarning)
{
    if (m_seatbeltWarning != seatbeltWarning)
    {
        m_seatbeltWarning = seatbeltWarning;
        emit seatbeltWarningChanged();
    }
}

void CarDataModel::setHeadlightsOn(bool headlightsOn)
{
    if (m_headlightsOn != headlightsOn)
    {
        m_headlightsOn = headlightsOn;
        emit headlightsOnChanged();
    }
}

void CarDataModel::setHighBeamOn(bool highBeamOn)
{
    if (m_highBeamOn != highBeamOn)
    {
        m_highBeamOn = highBeamOn;
        emit highBeamOnChanged();

        // 如果打开远光灯，确保近光灯也打开
        if (highBeamOn && !m_headlightsOn)
        {
            setHeadlightsOn(true);
        }

        if (highBeamOn)
        {
            setStatusMessage("远光灯已打开");
        }
        else
        {
            setStatusMessage("远光灯已关闭");
        }
    }
}

void CarDataModel::setOilLife(int oilLife)
{
    if (m_oilLife != oilLife)
    {
        m_oilLife = oilLife;
        emit oilLifeChanged();
    }
}

void CarDataModel::setAvgSpeed(double avgSpeed)
{
    if (m_avgSpeed != avgSpeed)
    {
        m_avgSpeed = avgSpeed;
        emit avgSpeedChanged();
    }
}

void CarDataModel::setAvgFuelConsumption(double avgFuelConsumption)
{
    if (m_avgFuelConsumption != avgFuelConsumption)
    {
        m_avgFuelConsumption = avgFuelConsumption;
        emit avgFuelConsumptionChanged();
    }
}

void CarDataModel::setTripDistance(int tripDistance)
{
    if (m_tripDistance != tripDistance)
    {
        m_tripDistance = tripDistance;
        emit tripDistanceChanged();
    }
}

void CarDataModel::toggleEngine()
{
    setEngineRunning(!m_engineRunning);
}

void CarDataModel::toggleHandbrake()
{
    setHandbrakeOn(!m_handbrakeOn);
}

void CarDataModel::toggleHeadlights()
{
    setHeadlightsOn(!m_headlightsOn);
}

void CarDataModel::toggleHighBeam()
{
    setHighBeamOn(!m_highBeamOn);
}

void CarDataModel::resetTrip()
{
    setTripDistance(0);
    setAvgSpeed(0);
    setAvgFuelConsumption(0);
    setStatusMessage("行程数据已重置");
}

void CarDataModel::updateTime()
{
    emit timeChanged();
}

// 平滑过渡函数，用于当前值逐渐接近目标值
int smoothTransition(int current, int target, int step)
{
    if (current < target)
    {
        return qMin(current + step, target);
    }
    else if (current > target)
    {
        return qMax(current - step, target);
    }
    return current;
}

void CarDataModel::simulateData()
{
    if (m_engineRunning)
    {
        // 每隔2秒随机生成新的目标值
        static int counter = 0;
        if (counter++ >= 40)
        { // 40 * 50ms = 2000ms
            counter = 0;
            if (!m_handbrakeOn)
            {
                // 设置新的目标速度
                m_targetSpeed = QRandomGenerator::global()->bounded(20, 120);

                // 根据速度计算合理的转速
                // 模拟不同速度下的转速变化，模拟变速箱换挡
                if (m_targetSpeed < 20)
                {
                    // 低速：1档
                    m_targetRpm = 800 + m_targetSpeed * 100;
                }
                else if (m_targetSpeed < 40)
                {
                    // 中低速：2档
                    m_targetRpm = 1300 + m_targetSpeed * 40;
                }
                else if (m_targetSpeed < 70)
                {
                    // 中速：3档
                    m_targetRpm = 1500 + m_targetSpeed * 25;
                }
                else if (m_targetSpeed < 100)
                {
                    // 中高速：4档
                    m_targetRpm = 1800 + m_targetSpeed * 15;
                }
                else
                {
                    // 高速：5档
                    m_targetRpm = 2000 + m_targetSpeed * 10;
                }

                // 添加一些随机变化，让转速不那么机械
                m_targetRpm += QRandomGenerator::global()->bounded(-200, 200);

                // 确保转速在合理范围内
                m_targetRpm = qBound(800, m_targetRpm, 6000);
            }

            // 随机更新水温和燃油目标值
            if (QRandomGenerator::global()->bounded(100) < 20)
            {
                m_targetWaterTemp = 85 + QRandomGenerator::global()->bounded(20);
                m_targetFuelLevel = qMax(0, m_fuelLevel - 1);
                setRemainingKm(qMax(0, m_remainingKm - 1));
            }
        }

        // 平滑过渡到目标值
        if (!m_handbrakeOn)
        {
            // 加速时转速先升高，然后速度跟上
            // 速度变化会带动转速变化
            int speed = smoothTransition(m_speed, m_targetSpeed, 2);

            // 当速度发生变化时，转速也会有波动
            if (speed != m_speed)
            {
                // 更新当前转速目标值，增加动态性
                if (speed > m_speed)
                {
                    // 加速时，转速先升高
                    m_targetRpm += (speed - m_speed) * 20;
                }
                else if (m_targetRpm > 1000)
                {
                    // 减速时，转速会下降
                    m_targetRpm -= (m_speed - speed) * 10;
                }

                // 确保转速在合理范围内
                m_targetRpm = qBound(800, m_targetRpm, 6000);
            }

            setRpm(smoothTransition(m_rpm, m_targetRpm, 30));
            setSpeed(speed);

            // 缓慢增加行程
            if (counter % 20 == 0 && m_speed > 0)
            {
                setTripDistance(m_tripDistance + 1);
            }
        }
        else
        {
            // 手刹拉起时，速度平滑降至0
            setSpeed(smoothTransition(m_speed, 0, 3));

            // 怠速
            m_targetRpm = 800;
            setRpm(smoothTransition(m_rpm, m_targetRpm, 30));
        }
    }
    else
    {
        // 发动机关闭，RPM和速度平滑降至0
        setRpm(smoothTransition(m_rpm, 0, 20));
        setSpeed(smoothTransition(m_speed, 0, 3));
    }

    // 平滑更新水温和燃油
    setWaterTemp(smoothTransition(m_waterTemp, m_targetWaterTemp, 1));
    setFuelLevel(smoothTransition(m_fuelLevel, m_targetFuelLevel, 1));
}
